<?php

namespace App\Services;

use App\Interfaces\RoleInterface;
use Illuminate\Support\Facades\DB;

class RoleService implements RoleInterface
{

    public function getUserRoles(array $arr): array
    {
        $res = DB::table('roles')->where('deleted',0)->whereIn('roleId',$arr)->get()->all();
        return $res;
    }

    public function getAllRoles(): array
    {
        $res = DB::table('roles')->where('deleted',0)->get()->all();
        return $res;
    }

    public function getRolePage(array $params = [], int $page = 1, int $limit = 10): array
    {
        $where = array(
            ['deleted',0],
            ['roleName','like','%'.$params['roleName'].'%'],
            ['roleCode','like','%'.$params['roleCode'].'%'],
        );
        if (!empty($params['comments'])){
            $where[] = ['comments', 'like', '%' . $params['comments'] . '%'];
        }
        $sort = empty($params['sort'])?'roleId':$params['sort'];
        $order = empty($params['order'])?'ASC':$params['order'];
        $res = DB::table('roles')
            ->where($where)
            ->offset($page - 1)
            ->orderBy($sort,$order)
            ->paginate($limit);
        $data['count'] = $res->total();
        $data['list'] = $res->items();
        return $data;
    }

    public function getRoleById(int $id)
    {
        $res = DB::table('roles')->where(['deleted'=>0,'roleId'=>$id])->get()->first();
        return $res;
    }

    public function updateRoleById(int $id, array $data): int
    {
        $res = DB::table('roles')->where('roleId',$id)->update($data);
        return $res;
    }

    public function createRole(array $data): int
    {
        $res = DB::table('roles')->insertGetId($data);
        return $res;
    }

    public function updateBatch(array $roleIds, array $data): int
    {
        $res = DB::table('roles')->whereIn('roleId',$roleIds)->update($data);
        return $res;
    }
}
